/**to load upload parameter from xml and deal upload file
 * by fuzhou huilin corp.ltd @author lms 2016.12.18
 * last update by @author lms 2016.12.18
 */
package com.fzrskj.cloud.free.core.tool;

import ms.core.consts.SysErr;
import ms.core.support.UploadParam;
import ms.core.tool.StrTool;
import ms.core.tool.XmlCodeParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class CXmlUploadParser {
	//private declarations
	private static Map<String, UploadParam> mpTable;
	private static Logger logger = LogManager.getLogger(CXmlUploadParser.class);

	//to initialize global session object
	static{
		mpTable = new HashMap<String, UploadParam>();
		CXmlUploadParser xmlParser = new CXmlUploadParser();
		xmlParser.parserXml("/config/upload.xml", mpTable);
	}

	private void parserXml(String fileName, Map<String, UploadParam> table){
		try{
			InputStream in = this.getClass().getResourceAsStream(fileName);
			SAXReader reader = new SAXReader();
			Document doc = reader.read(in);
			Element root = doc.getRootElement();
			List<Element> items = root.elements();
			for(Element item : items){
				UploadParam p = new UploadParam();
				p.setUpname(item.attributeValue("upname"));
				p.setDescription(item.attributeValue("desc"));
				p.setClassName(item.attributeValue("className"));
				p.setFunc(item.attributeValue("function"));
				p.setAuthUtype(item.attributeValue("authUtype"));
				p.setFilters(item.attributeValue("filters"));
				p.setFileMaxSize(StrTool.strToIntDef(item.attributeValue("maxsize"),0));
				p.setMaxNum(StrTool.strToIntDef(item.attributeValue("maxnum"),0));
				p.setSavePath(item.attributeValue("savepath"));
				table.put(p.getUpname(),p);
			}
			in.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	/**
	 * to get upload parameter by 
	 * @param uptype sort of uploading file
	 * @return UploadParam Object for success, return null when not exists
	 */
	public static UploadParam getUploadParam(String uptype){
		if (StrTool.isBlankStr(uptype)) return null;
		return mpTable.get(uptype);
	}

	public static Map<String, UploadParam> getUploadParams() {
		return mpTable;
	}
	
	/**to deal uploaded files
	 * by lms 2016.12.18
	 * @param up UploadParam parameter
	 * @param sid current login user session id
	 * @param p json parameter
	 * @param uploadedFiles uploaded files
	 * @return deal result string
	 */
	public static String handleUploadedFile(UploadParam up, String sid, String p, String uploadedFiles){
		if (up==null)
			return XmlCodeParser.formatResultTips(false, SysErr.FILE_UNKNOW_UPLOAD);

		if (StrTool.isBlankStr(up.getClassName()) || StrTool.isBlankStr(up.getFunc()))		
			return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS,String.format("{\"files\":%s}",uploadedFiles));
		try {
			Class<?> cls=Class.forName(up.getClassName());
			Method method = cls.getMethod(up.getFunc(), String.class, String.class, String.class);
			Integer ret = (Integer) method.invoke(cls.newInstance(), sid, p, uploadedFiles);
			if (ret>0){
				String data = String.format("{\"files\":%s}",uploadedFiles);
				return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS,data);
			}

			return XmlCodeParser.formatResultTips(true, SysErr.FILE_UPLOAD_FAILURE);
		} catch (Exception e) {
			logger.error(e,e);
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_CRASH);
		}
	}
}